package android.support.v4.app;



import com.lab.app.BaseFragment;

import java.util.ArrayList;

/**
 * Created by ak
 */
public class SuperFragmentUtil {
    /**
     * 获取fragment堆栈
     *
     * @param fragmentManager
     * @return
     */
    public static ArrayList<Fragment> getAddedFragments(FragmentManager fragmentManager) {
        return ((FragmentManagerImpl) fragmentManager).mAdded;
    }

    /**
     * 获取fragmentManager最上层的Fragment
     *
     * @param fragmentManager
     * @return
     */
    public static Fragment getCurrentTopFragment(FragmentManager fragmentManager) {
        FragmentManagerImpl impl = ((FragmentManagerImpl) fragmentManager);
        if (impl != null && impl.mBackStack != null && impl.mBackStack.size() > 0) {
            int count = impl.mBackStack.size();
            final BackStackRecord bss = impl.mBackStack.get(count - 1);
            BackStackRecord.Op option = bss.mTail;
            Fragment fragment = option.fragment;
            return fragment;
        }
        return null;
    }

    /**
     * 移除Fragment
     * 嵌套
     *
     * @param fragmentManager
     * @return
     */
    public static boolean tryToPopUpFragment(FragmentManager fragmentManager) {
        FragmentManagerImpl impl = ((FragmentManagerImpl) fragmentManager);
        if (impl != null && impl.mBackStack != null && impl.mBackStack.size() > 0) {
            int count = impl.mBackStack.size();
            final BackStackRecord bss = impl.mBackStack.get(count - 1);
            BackStackRecord.Op option = bss.mTail;
            Fragment fragment = option.fragment;
            if (fragment instanceof BaseFragment) {
                if (((BaseFragment) fragment).onBackPressed()) {
                    return true;
                } else {
                    return false;
                }
            }
        }
        return false;
    }

    /**
     * 移除Fragment
     * 嵌套
     *
     * @param fragmentManager
     * @return
     */
    public static boolean tryToDirectPopUpFragment(FragmentManager fragmentManager) {
        FragmentManagerImpl impl = ((FragmentManagerImpl) fragmentManager);
        try {
            if (impl != null && impl.mBackStack != null && impl.mBackStack.size() > 0) {
                return fragmentManager.popBackStackImmediate();
            }
        } catch (Exception e) {

        }
        return false;
    }

    /**
     * 获取被Add的Fragment
     *
     * @param fragmentManager
     * @return
     */
    public static Fragment getCurrentTopAddedFragment(FragmentManager fragmentManager) {
        FragmentManagerImpl impl = ((FragmentManagerImpl) fragmentManager);
        if (impl != null && impl.mAdded != null && impl.mAdded.size() > 0) {
            Fragment fragment = impl.mAdded.get(impl.mAdded.size() - 1);
            return fragment;
        }
        return null;
    }

}
